package net.qiqbframework.modelling.domain;

import net.qiqbframework.messaging.Message;
import net.qiqbframework.messaging.annotation.HandlerParameterResolver;
import net.qiqbframework.messaging.annotation.HandlerParameterResolverFactory;
import net.qiqbframework.persisthanding.PersistHandler;
import net.qiqbframework.persisthanding.PersistMessage;
import net.qiqbframework.common.utils.AnnotationUtil;

import java.lang.reflect.Executable;
import java.lang.reflect.Parameter;

/**
 * 持久化第二个参数聚合快照
 */
public class PersistHandlerSecendParameterResolverFactory implements HandlerParameterResolverFactory {


    @Override
    public HandlerParameterResolver createInstance(Executable executable, Parameter[] parameters, int parameterIndex) {
        Class<?> parameterType = parameters[parameterIndex].getType();
        if (parameterIndex == 1 && AnnotationUtil.isAnnotationPresent(executable, PersistHandler.class)) {
            if (AnnotationUtil.isAnnotationPresent(parameterType, AggregateRoot.class)) {
                return new HandlerParameterResolver() {

                    @Override
                    public Object resolveParameter(Message message) {
                        if (message instanceof PersistMessage<?> persistMessage) {

                            return persistMessage.getMetaData().get("aggregateRootSnapshot");
                        }
                        return null;
                    }

                    @Override
                    public boolean support(Message message) {
                        if (message instanceof PersistMessage<?> persistMessage) {
                            return !persistMessage.isNew();
                        }
                        return false;
                    }
                };
            }
        }
        //


        return null;
    }
}
